package com.icart.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icart.WxTemplate.TemplateData;
import com.icart.WxTemplate.WxTemplate;
import com.icart.comm.AjaxRspResult;
import com.icart.context.HttpUserContext;
import com.icart.context.storage.ContextStorage;
import com.icart.context.storage.SessionContextStorageImpl;
import com.icart.repositories.ServbookRepository;
import com.icart.repositories.ServbookitemRepository;
import com.icart.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class ShopController {

    @Autowired
    HttpServletRequest request;
    @Autowired
    private ServbookRepository ServbookRepository;
    @Autowired
    private ServbookitemRepository ServbookitemRepository;
    @Autowired
    HttpSession session;
    @Autowired
    private RestTemplate template;

    @RequestMapping("/shoplist")
    public String shoplist(@RequestParam(name = "data",required = false) String data,
                           @RequestParam(name = "itemnum",required = false) String itemnum,
                           @RequestParam(name = "itemsel",required = false) String itemsel,Model model) {
        model.addAttribute("data",data);
        model.addAttribute("itemnum",itemnum);
        model.addAttribute("itemsel",itemsel);
        Object lat=session.getAttribute("lat");//纬度
        Object lon=session.getAttribute("lon");//经度
        model.addAttribute("lat",lat);
        model.addAttribute("lon",lon);

        String sql="select packid,packname from bi_servpack where packid in(";//查询分组
        String shopsql="select DISTINCT(bc.chnid),bc.tel,bc.chnname,bc.addr,(select p.picurl from bi_chnpic p where p.chnid=bc.chnid and p.isdefault=1)picurl," +
                "(select AVG(wc.commstar) from wo_comment wc where  wc.oid in(select oid from wo_info where chnid=bc.chnid))com," +
                "(select count(*) from wo_info w where w.chnid=bc.chnid)num," +
                "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(( "+lat+" * PI() / 180 - bc.lat * PI() / 180) / 2),2) + COS("+lat+" * PI() / 180) * COS(bc.lat * PI() / 180) * POW(SIN((" + lon+" * PI() / 180 - bc.lon * PI() / 180) / 2 ),2)))*10) AS distance" +
                " from bi_chn bc,bi_servitem bs,bi_servitemchn bsc " +
                "where (bc.chnid=bs.chnid or bc.chnid=bsc.chnid) and bs.isbook=1 and bsc.servitemid=bs.servitemid and bs.servitemid in(";//根据项目查找门店
        String[] d1=data.split(";");
        int i=0;
        List itemlist=new ArrayList();
        for(String group:d1){
            if(i==0){
                i++;
                continue;
            }
            String[] d2=group.split(",");//d2[0]为分组编号，其余为项目
            String sql1="";
            sql1+="select bs.servitemid,bs.servitemname,bp.packid,bs.chnid from bi_servitem bs,bi_servpackitem bp where bp.servitemid=bs.servitemid and bp.packid="+d2[0]+" and bp.servitemid in(";
            if(i==1){
                sql+=d2[0];
            } else {
                sql+=","+d2[0];
            }
            for(int j=1;j<d2.length;j++){ //循环项目
                if(j==1){
                    sql1+=d2[j];
                } else {
                    sql1+=","+d2[j];
                }
                if(j==1&&i==1){
                    shopsql+=d2[j];
                } else {
                    shopsql+=","+d2[j];
                }
            }
            sql1+=")";
            List ilist=ServbookRepository.createNativeQuery(sql1);
            itemlist.addAll(ilist);
            i++;
        }
        sql+=")";
        shopsql+=")";
        String add="广东省 广州市 番禺区";
        String addcode="440113";
        if(session.getAttribute("address")!=null) {
            add = session.getAttribute("address").toString().equals("") ? "广东省 广州市 番禺区" : session.getAttribute("address").toString();
            addcode = session.getAttribute("adcode").toString().equals("0") ? "440113" : session.getAttribute("adcode").toString();
        }
        String ar=request.getParameter("ar")==null?add:request.getParameter("ar");
        String area=addcode;
        if(request.getParameter("area")!=null){
            area=request.getParameter("area");
        }
        model.addAttribute("ar",ar);
        model.addAttribute("area",area);
        shopsql+=" and bc.addrregion like '%"+area+"%'";

        if(Tools.notEmpty(request.getParameter("search"))){
            String search=request.getParameter("search");
            shopsql+=" and bc.chnname like '%"+search+"%'";
            model.addAttribute("search",search);
        }
//        if(Tools.notEmpty(request.getParameter("shoptype"))){
//            String shoptype=request.getParameter("shoptype");
//            model.addAttribute("shoptype",shoptype);
//            switch (shoptype){
//                case "2":shopsql+="";String sst="全部门店";model.addAttribute("setshoptype",sst);break;
//                case "1":shopsql+=" and bc.isbook=1";String sst1="可预约";model.addAttribute("setshoptype",sst1);break;
//                case "0":shopsql+=" and bc.isbook=0";String sst2="不可预约";model.addAttribute("setshoptype",sst2);break;
//            }
//        }
        if(Tools.notEmpty(request.getParameter("type"))){
            String type=request.getParameter("type");
            model.addAttribute("type",type);
            switch (type){
                case "1":shopsql+=" order by com desc,distance";String sst="默认排序";model.addAttribute("settype",sst);break;
                case "2":shopsql+=" order by distance";String sst1="附近优先";model.addAttribute("settype",sst1);break;
                case "3":shopsql+=" order by com desc";String sst2="评分最高";model.addAttribute("settype",sst2);break;
                case "4":shopsql+=" order by num desc";String sst3="服务次数";model.addAttribute("settype",sst3);break;
            }
        }

        List glist=ServbookRepository.createNativeQuery(sql);
        List shoplist=ServbookRepository.createNativeQuery(shopsql);
        String busiid=request.getParameter("busiid");
        model.addAttribute("busiid",busiid);
        model.addAttribute("glist",glist);//项目分组数据
        model.addAttribute("itemlist",itemlist);//项目数据
        model.addAttribute("itemsel",itemsel);//已选项目数
        model.addAttribute("itemnum",itemnum);//项目数量
        model.addAttribute("shoplist",shoplist);//门店
        return "shop/shoplist";
    }

    @RequestMapping("/shop")
    public String shop(Model model) {
        Object lat=session.getAttribute("lat");//纬度
        Object lon=session.getAttribute("lon");//经度
        model.addAttribute("lat",lat);
        model.addAttribute("lon",lon);
        String shopsql="select DISTINCT(bc.chnid),bc.isbook,bc.chnname,bc.addr,(select p.picurl from bi_chnpic p where p.chnid=bc.chnid and p.isdefault=1)picurl," +
                "(select AVG(wc.commstar) from wo_comment wc where  wc.oid in(select oid from wo_info where chnid=bc.chnid))com," +
                "(select count(*) from wo_info w where w.stat not in(-1) and w.chnid=bc.chnid)num," +
                "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(( "+lat+" * PI() / 180 - bc.lat * PI() / 180) / 2),2) + COS("+lat+" * PI() / 180) * COS(bc.lat * PI() / 180) * POW(SIN((" + lon+" * PI() / 180 - bc.lon * PI() / 180) / 2 ),2)))*10) AS distance" +
                " from bi_chn bc " +
                "where 1=1 ";
        String add="广东省 广州市 番禺区";
        String addcode="440113";
        if(session.getAttribute("address")!=null) {
             add = session.getAttribute("address").toString().equals("") ? "广东省 广州市 番禺区" : session.getAttribute("address").toString();
            addcode = session.getAttribute("adcode").toString().equals("0") ? "440113" : session.getAttribute("adcode").toString();
        }
        String ar=request.getParameter("ar")==null?add:request.getParameter("ar");
        String area=addcode;
        if(request.getParameter("area")!=null){
            area=request.getParameter("area");
        }
        model.addAttribute("ar",ar);
        model.addAttribute("area",area);
        shopsql+=" and bc.addrregion like '%"+area+"%'";

        if(Tools.notEmpty(request.getParameter("search"))){
            String search=request.getParameter("search");
            shopsql+=" and bc.chnname like '%"+search+"%'";
            model.addAttribute("search",search);
        }

        if(Tools.notEmpty(request.getParameter("shoptype"))){
            String shoptype=request.getParameter("shoptype");
            model.addAttribute("shoptype",shoptype);
            switch (shoptype){
                case "2":shopsql+="";String sst="全部门店";model.addAttribute("setshoptype",sst);break;
                case "1":shopsql+=" and bc.isbook=1";String sst1="可预约";model.addAttribute("setshoptype",sst1);break;
                case "0":shopsql+=" and bc.isbook=0";String sst2="不可预约";model.addAttribute("setshoptype",sst2);break;
            }
        }
        if(Tools.notEmpty(request.getParameter("type"))){
            String type=request.getParameter("type");
            model.addAttribute("type",type);
            switch (type){
                case "1":shopsql+=" order by com desc,distance";String sst="默认排序";model.addAttribute("settype",sst);break;
                case "2":shopsql+=" order by distance";String sst1="附近优先";model.addAttribute("settype",sst1);break;
                case "3":shopsql+=" order by com desc";String sst2="评分最高";model.addAttribute("settype",sst2);break;
                case "4":shopsql+=" order by num desc";String sst3="服务次数";model.addAttribute("settype",sst3);break;
            }
        }

//        //定位
//        /*获取微信的token*/
//        String url="http://pay.wechat.ikartek.com/jssdk/api.php?url=http://testwx.ikartek.com/shop&token=";
//        HomeController.gettoken(model,template,url);

        List shoplist=ServbookRepository.createNativeQuery(shopsql);

        model.addAttribute("shoplist",shoplist);//门店
        return "shop/shop";
    }

    @RequestMapping(value = "/shopserv",method = RequestMethod.GET)
    @ResponseBody
    public AjaxRspResult servdata(@RequestParam(name = "shopid",required = false) String shopid) {
       String sql="select bs.staffid,bs.staffname,(select count(*) from wo_info w where w.stat not in(-1) and w.chnid=bs.chnid and w.servman=bs.staffid)num," +
               "(select AVG(wc.commstar) from wo_commentitem wc where wc.objid=bs.staffid and wc.itemid in(select itemid from wo_commentdef where itemtype='serv'))com from bi_chnstaff bs where bs.status=1 and bs.post='service' and bs.chnid="+shopid;
        List servlist=ServbookRepository.createNativeQuery(sql);
        AjaxRspResult arr=new AjaxRspResult();
        arr.setResult(servlist);
        return arr;
    }

    @RequestMapping(value = "/shoporder",method = RequestMethod.POST)
    @ResponseBody
    public AjaxRspResult shoporder() {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");
        Long custid=userContext.getCustid();
        String sql="select cc.regdate,cc.curkilo,cc.custcarid,cc.carno,c.custname,c.mobile from cu_custinfo c,cu_custcar cc where cc.setdefault=1 and cc.custid=c.custid and c.custid="+custid;
        List cust=ServbookRepository.createNativeQuery(sql);
        System.out.print(cust);
        String cust2 = JSON.toJSONString(cust);
        cust2=cust2.replace("[", "");
        cust2=cust2.replace("]", "");
        System.out.print(cust2);
        JSONObject cust3 = JSON.parseObject(cust2);//将list转换为json对象

        String shop=request.getParameter("shop");
        JSONObject jsonObject= JSON.parseObject(shop);
        System.out.println(jsonObject);

        JSONArray shoplist=jsonObject.getJSONArray("shoplist");

        Date dates=new Date();
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String creattime=format.format(dates);//获取当前系统时间
        Long times=dates.getTime();//获取当前系统时间,暂时用作预约流水号


        Long custcarid=Long.parseLong(cust3.getString("custcarid"));
        String carno=cust3.getString("carno");
        String regdate="";//上路时间
        if(Tools.notEmpty(cust3.getString("regdate"))){
            DateFormat format2=new SimpleDateFormat("yyyy-MM-dd");
            Long tt=Long.parseLong(cust3.getString("regdate"));
            regdate=format2.format(tt);
        }
        Long curkilo=0L;//里程
        if(Tools.notEmpty(cust3.getString("curkilo"))){
            curkilo=Long.parseLong(cust3.getString("curkilo"));
        }
        String linkman=cust3.getString("custname");
        String linktel=cust3.getString("mobile");
        Long busiid2=Long.parseLong(jsonObject.getString("busiid"));//业务分类
        Long chnid=Long.parseLong(jsonObject.getString("shopid"));//门店
        String date=jsonObject.getString("date");//预约日期
        String time=jsonObject.getString("time");//预约时间
        String bookcode=bookcode();
        Long servid=jsonObject.getString("servid")==null?0:Long.parseLong(jsonObject.getString("servid"));//预约顾问
        Integer f=ServbookRepository.insert(times,custid,custcarid,carno,curkilo,regdate,linkman,linktel,busiid2,chnid,date,time,servid,creattime,0,bookcode);

        Long packid=0L;
        int cnt;
        Long servitemid=0L;
        int flag=0;
        for(int i=0;i<shoplist.size();i++){
            if(flag==0){
                packid=Long.parseLong(shoplist.get(i).toString());
            }
            if(flag==1){
                servitemid=Long.parseLong(shoplist.get(i).toString());
            }
            if(flag==2){
                cnt=Integer.parseInt(shoplist.get(i).toString());
                ServbookitemRepository.insert(times,servitemid,cnt,packid,busiid2);
                flag=0;
                continue;
            }
            flag++;
        }

        //发送模板消息
        String chnname=jsonObject.getString("chnname");//门店名称
        String shoptel=jsonObject.getString("shoptel");//联系方式

        WxTemplate wxtemplate=new WxTemplate();
        String openid=request.getSession().getAttribute("openid").toString();
        wxtemplate.setTouser(openid);//用户的OPENID
        wxtemplate.setTopcolor("#000000");
        wxtemplate.setTemplate_id("h-MqpqoU3jNfI6GozAFu7tjAt4Lfdoaeps0yWv2MmDs");
        Map<String,TemplateData> m = new HashMap<String,TemplateData>();
        TemplateData first = new TemplateData();
        first.setColor("#000000");
        first.setValue("尊敬的"+carno+"车主，您的预约已提交成功，请耐心等待门店确认");
        m.put("first", first);
        TemplateData keyword1 = new TemplateData();
        keyword1.setColor("#173177");
        keyword1.setValue(date+" "+time);//预约时间
        m.put("keyword1", keyword1);
        TemplateData keyword2 = new TemplateData();
        keyword2.setColor("#173177");
        keyword2.setValue(chnname);//预约门店
        m.put("keyword2", keyword2);
        TemplateData keyword3 = new TemplateData();
        keyword3.setColor("#173177");
        keyword3.setValue(shoptel);//联系方式
        m.put("keyword3", keyword3);
        TemplateData remark = new TemplateData();
        remark.setColor("#000000");
        remark.setValue("如有疑问请通过联系方式联系门店，谢谢!");
        m.put("remark", remark);
        wxtemplate.setData(m);
        String data = JSONObject.toJSONString(wxtemplate).toString();
        WxUtilController w=new WxUtilController();
        w.sendMessage(data,template,request);

        AjaxRspResult arr=new AjaxRspResult();
        return arr;
    }

    @RequestMapping(value = "/shopprice",method = RequestMethod.GET)
    @ResponseBody
    public AjaxRspResult shopprice() {
        String data=request.getParameter("data");
        JSONObject jsonObject= JSON.parseObject(data);
        String shopid=jsonObject.getString("shopid");//门店编号
        JSONArray shoplist=jsonObject.getJSONArray("item");
        String sql="select whprice,servitemid from bi_servitemprice where chnid="+shopid+" and carkindid=0 and servitemid in(";
        for(int i=0;i<shoplist.size();i++){
            if(i==0){
                sql+=shoplist.get(i);
            } else {
                sql+=","+shoplist.get(i);
            }
        }
        sql+=")";
        List shopprice=ServbookRepository.createNativeQuery(sql);
        AjaxRspResult arr=new AjaxRspResult();
        arr.setResult(shopprice);
        return arr;
    }

    public static String bookcode(){
        String bookcode="";
        Date date=new Date();
        DateFormat format2=new SimpleDateFormat("HHmmss");
        String time=format2.format(date);//获取当前系统时间
        String chars = "QWERTYUIOPASDFGHJKLZXCVBNM";
        bookcode=(chars.charAt((int)(Math.random() * 26)))+time;
        return bookcode;
    }
}